package com.creative.xcx.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.creative.core.controller.BaseController;
import com.creative.core.domain.AjaxResult;
import com.creative.xcx.domain.UserFavorite;
import com.creative.xcx.mapper.UserFavoriteMapper;
import com.creative.xcx.service.UserFavoriteService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.creative.xcx.domain.constant.common.CACHE_FAVORITE_KEY;

/**
 * @author ling
 * @description 用户收藏
 * @date 2025-03-23
 */
@RestController
@RequestMapping(value = "/UserFavorite")
public class UserFavoriteController extends BaseController {

    @Resource
    private UserFavoriteService userFavoriteService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserFavoriteMapper userFavoriteMapper;

    /**
     * 新增(收藏素材)
     *
     * @author ling
     * @date 2025/03/23
     **/
    @PostMapping
    public AjaxResult insert(@RequestBody UserFavorite userFavorite) {
        return toAjax(userFavoriteService.insert(userFavorite));
    }

    // 检查是否收藏
    @PostMapping("/isCollected")
    public AjaxResult isCollected(@RequestBody UserFavorite userFavorite) {
        String userId = (String) StpUtil.getLoginId();
        String key = CACHE_FAVORITE_KEY + userId;
//      判断用户缓存是否存在
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(key))) {
//            重建缓存
            List<UserFavorite> dbData = userFavoriteMapper.selectByUserId(userId);
            if (!dbData.isEmpty()) {
//           遍历数据，将数据添加到Redis中
                for (UserFavorite favorite : dbData) {
                    stringRedisTemplate.opsForZSet().add(CACHE_FAVORITE_KEY + userId, favorite.getMaterialId(), favorite.getCreateTime().getTime());
                }
            }
        }

//        判断当前用户是否已收藏该素材
        return success().put("isCollect", stringRedisTemplate.opsForZSet().score(key, userFavorite.getMaterialId()) != null);
    }

    /**
     * 刪除单个
     *
     * @author ling
     * @date 2025/03/23
     **/
    @PutMapping("/")
    public AjaxResult delete(@RequestBody UserFavorite userFavorite) {
        return toAjax(userFavoriteService.delete(userFavorite));
    }

    /**
     * 批量刪除
     *
     * @author ling
     * @date 2025/03/23
     **/

    @DeleteMapping("/batch")
    public AjaxResult deleteBatch(@RequestBody Long[] ids) {
        return toAjax(userFavoriteService.deleteBatch(ids));
    }


    /**
     * 更新
     *
     * @author ling
     * @date 2025/03/23
     **/
    @PutMapping("/update")
    public AjaxResult update(@RequestBody UserFavorite userFavorite) {
        return toAjax(userFavoriteService.update(userFavorite));
    }


    /**
     * 查询 根据主键 id 查询
     *
     * @author ling
     * @date 2025/03/23
     **/
    @GetMapping(value = "/{id}")
    public AjaxResult selectById(@PathVariable("id") Long id) {

        if (id == null) {
            return error("参数为空");
        }
        return success(userFavoriteService.selectById(id));
    }

    /**
     * 查询 分页查询(带条件)
     *
     * @author ling
     * @date 2025/03/23
     **/
    @GetMapping("/list")
    public AjaxResult selectUserFavoriteList(UserFavorite userFavorite) {

        return success(userFavoriteService.selectUserFavoriteList(userFavorite));
    }

    /**
     * 批量导出
     *
     * @author ling
     * @date 2025/03/23
     **/
    @PostMapping("/export")
    public void export(@RequestBody Long[] ids, HttpServletResponse response) throws IOException {
        //        判断ids是否为空
        if (ids == null || ids.length == 0) {
            // ids 为空或未初始化时执行的代码
            throw new RuntimeException("ids为空");
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("用户收藏" + System.currentTimeMillis(), StandardCharsets.UTF_8);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), UserFavorite.class)
                .sheet("用户收藏")
                .doWrite(() -> {
                    // 查询数据
                    return userFavoriteService.exportBatch(ids);
                });
        logger.info("导出成功");
    }
}
